<?php

/**
 * Description of Wechatlink
 * 和微信服务器对接
 * @author ahfee
 */
class WechatlinkController extends \Yaf_Controller_Abstract{
    
    public $myToken = null;

    public function indexAction(){
        exit;
    }
        
    public function validAction(){
        $echoStr = $_GET["echostr"];        
        $config = \Yaf_Registry::get('configarr');
        $this->myToken = $config['wechat']['myToken'];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
        exit;
    }
    
    private function checkSignature(){
        // you must define TOKEN by yourself
        if (!$this->myToken) {
            die('token is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($this->myToken, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
                return true;
        }else{
                return false;
        }
    }
    
    public function geiUserListAction(){
        $token = tools_help::getToken();
        
        //获取openid 列表
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token;
        $result = tools_help::weixinCurlGet($url);
        $result = json_decode($result,true);  
        
//  Array  返回结果
//(
//    [total] => 2
//    [count] => 2
//    [data] => Array
//        (
//            [openid] => Array
//                (
//                    [0] => oNfL7sgYdVoSyp01ioMnFpzikBRQ
//                    [1] => oNfL7srg_wFeIqvQYAbbyjmMutQU
//                )
//
//        )
//
//    [next_openid] => oNfL7srg_wFeIqvQYAbbyjmMutQU
//)       
        if(!isset($result['data']['openid'])){
            die('获取openid有误！');
        }else{
            //获取用户信息
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token;     
            $userList = array();
            foreach($result['data']['openid'] as $v){
                $url .= '&openid='.$v;
                $result = tools_help::weixinCurlGet($url);
                $result = json_decode($result,true); 
                print_r($result);exit;
            }
        }
        print_R($result);exit;
 
    } 
    
}
